import Router from '@koa/router';
import { getUploadUrl, getDownUrl } from '../common/oss.js';
import response from '../response.js';
import moment from 'moment';
import path from 'path';
import { WxService } from '../common/wx.js';
import { checkIdCard } from '../common/sm.js';
import db from '../mysqlHelper.js';
import fs from 'fs';
import PizZip from 'pizzip';
import Docxtemplater from 'docxtemplater';
import ImageModule from 'docxtemplater-image-module-free';
import sizeOf from 'image-size'; // 导入 image-size 模块
import { uploadFile ,downloadFile} from '../common/oss.js';
import {sendSms} from '../common/sms.js'


// 获取当前模块的目录名
const __dirname =process.cwd();
let authCode = [];
const router = new Router();
router.prefix('/api');
router.post(`/oss/getUploadUrl`, async (ctx) => {

    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.filePath == null) {
        ctx.body = response.fail('缺少必填字段 文件路径');
        return;
    }
    let type = body.type || 'public';
    console.log(type);
    let url = await getUploadUrl(body.filePath, type);
    if (url instanceof Error) {
        ctx.body = response.fail(url.message);
        return;
    }
    ctx.body = response.success(url, '获取成功');

});
router.post(`/oss/getDownUrl`, async (ctx) => {

    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.filePath == null) {
        ctx.body = response.fail('缺少必填字段 文件路径');
        return;
    }
    let url = await getDownUrl(body.filePath);
    if (url instanceof Error) {
        ctx.body = response.fail(url.message);
        return;
    }
    ctx.body = response.success(url, '获取成功');

});
//数脉二要素验证接口
router.post('/sm/verifyIdCard', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.idCard == null) {
        ctx.body = response.fail('缺少必填字段 身份证号');
        return;
    }
    if (body.name == null) {
        ctx.body = response.fail('缺少必填字段 姓名');
        return;
    }
    let res = await checkIdCard(body.name, body.idCard);
    if (res instanceof Error) {
        ctx.body = response.fail(res.message);
        return;
    }
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    ctx.body = response.success(res.data, '验证成功');
});

router.post('/enterprise/getWorkLevel', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.enterprise_id == null) {
        ctx.body = response.fail('缺少必填字段 企业id');
        return;
    }
    let sql = `select * from batch where enterprise_id = ${body.enterprise_id} and start<=${moment().format('YYYYMMDD')} and end>=${moment().format('YYYYMMDD')} and type=0`;
    console.log("根据企业id获取有效批次", sql);
    let res = await db.query(sql);
    if (res instanceof Error) {
        ctx.body = response.fail(res.message);
        return;
    }
    if (res.length == 0) {
        ctx.body = response.fail('该企业当前无绑定的有效批次');
        return;
    }
    let batch = res[0];
    sql = `SELECT batch_bind.*,wl.name,wl.remark,wl.images,wl.brief_introduction,wl.detail,wl.score_template_id,wl.enroll_template_id,wl.enroll_condition
    ,type_work.name as work_name 
     FROM  batch_bind   LEFT JOIN   type_work_level wl  ON   batch_bind.work_type_level_id = wl.id  left join type_work on type_work.id = wl.type_id
     where batch_bind.batch_id = ${batch.id}`;
    console.log("根据批次id获取绑定的工种", sql);
    res = await db.query(sql);
    if (res instanceof Error) {
        ctx.body = response.fail(res.message);
        return;
    }
    if (res.length == 0) {
        ctx.body = response.fail('该企业报名批次无绑定的工种');
        return;
    }
    res[0].batch = batch
    ctx.body = response.success({ work_level: res, batch }, '获取成功');
});

router.post('/auth/sendSmsCode', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.phone == null) {
        ctx.body = response.fail('缺少必填字段 手机号');
        return;
    }
    let last = authCode.find(item => item.phone == body.phone);
    if (last && moment().diff(last.time, 'seconds') < 60) {
        ctx.body = response.fail('60秒内只能发送一次');
        return;
    }
    let code = Math.random().toString().slice(-6);
    let res = await sendSms(body.phone, code);
    if (res == false) {
        console.error(`手机号${body.phone}发送短信验证码失败`);
        ctx.body = response.fail('发送短信验证码失败');
        return;
    }
    console.log(`手机号${body.phone}验证码${code}成功`);
    authCode.push({ phone: body.phone, code, time: moment() })
    ctx.body = response.success({ code }, '发送成功');
});

router.post('/auth/checkSmsCode', async (ctx) => {

    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }

    if (body.code == null) {
        ctx.body = response.fail('缺少必填字段 验证码');
        return;
    }
    let last = authCode.find(item => item.code == body.code);
    if (last == null) {
        ctx.body = response.fail('验证码不存在');
        return;
    }
    if (moment().diff(last.time, 'minutes') > 5) {
        ctx.body = response.fail('验证码已过期');
        return;
    }
    //移除验证过的验证码
    authCode = authCode.filter(item => item.code != body.code);
    //移除所有过期的验证码
    authCode = authCode.filter(item => moment().diff(item.time, 'minutes') < 5);
    ctx.body = response.success('验证成功');

});

//替换word文档的内容
router.post('/docx/replace', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.templatePath == null) {
        ctx.body = response.fail('缺少必填字段 模板');
        return;
    }
    if (body.outFilePath == null) {
        ctx.body = response.fail('缺少必填字段 输出文件路径');
        return;
    }
    if (body.data == null) {
        ctx.body = response.fail('缺少必填字段 数据');
        return;
    }
    // 读取Word文档
    let filename=`${__dirname}${body.templatePath}`;
    const content = fs.readFileSync(filename, 'binary');
    let picMap = new Map();
    //扁历body.data,如果有图片，下载图片
    for (let key in body.data) {
        if (body.data[key].indexOf('.') != -1) {
            let data = await downloadFile(body.data[key]);
            //下载的数据写入到文件中
            console.log("下载的数据",data);
            // fs.writeFileSync(body.data[key], data);
            // let d2 =fs.readFileSync(body.data[key]);
            // console.log("下载的数据2",d2);



            if(data!=null){
                picMap.set(body.data[key], data);
            }
        }
    }
      
    // 配置图片模块
    const opts = {
        centered: false,
        getImage(tagValue, tagName) {
            // 确保路径是正确的，并且这里的输出可以帮助你调试
            let data = picMap.get(tagValue);
            return data;
          //  return fs.readFileSync(tagValue);
        },
        getSize(tagValue, tagName) {
            // 返回图片的尺寸，这里可以调整为适合文档的尺寸
            const dimensions = sizeOf(tagValue);
            // console.log("Getting size from:", tagValue, tagName, dimensions);
            return [dimensions.width, dimensions.height]; // 返回实际尺寸
        }
    };
    const imageModule = new ImageModule(opts);
    const zip = new PizZip(content);
    const doc = new Docxtemplater(zip, {
        paragraphLoop: true, // 保持段落循环（对保持样式很有帮助）
        linebreaks: true, // 支持在文本中直接使用换行符
        modules: [imageModule]
    });

    // 设置模板变量的值，这里的键必须与文档中的占位符相对应
    doc.setData(body.data);

    try {
        // 渲染文档，替换所有占位符
        doc.render();
    }
    catch (error) {
        const e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties,
        }
        console.log(JSON.stringify({ error: e }));
        // 处理错误情况
        ctx.body = response.fail(error.message);
        return;
    }

    const buf = doc.getZip()
        .generate({ type: 'nodebuffer' });
    
    let  tempPath= moment().format('YYYYMMDDHHmmss') + '.docx';
    // 将渲染后的文档写入到新的文件
    fs.writeFileSync(tempPath, buf);
   let  res =await uploadFile( body.outFilePath,tempPath);
   //删除临时文件
    fs.unlinkSync(tempPath);
    picMap.clear();
    if(res.code == 0){
        ctx.body = response.fail(res.msg);
        return;
    }
    ctx.body = response.success( res,'替换成功');
});


//接收图片并上传到阿里云OSS
router.post('/upload/image', async (ctx) => {
    const file = ctx.request.files.file; // 获取上传文件
//获取上传文件的数组
    if (file == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if(ctx.request.body.ossPath == null){
        ctx.body = response.fail('缺少必填字段 ossPath');
        return;
    }
    let type ='public';
    if(ctx.request.body.type){
        type = ctx.request.body.type;
    }
    //获取流里的数组
    let buffer = fs.readFileSync(file.filepath);
    let result = await uploadFile(ctx.request.body.ossPath, buffer,type);
    if (result.code == 0) {
        ctx.body = response.fail(result.msg);
        return;
    }
    ctx.body = response.success(result, '上传成功');
});

router.post('/upload/file', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.filePath == null) {
        ctx.body = response.fail('缺少必填字段 文件路径');
        return;
    } 
    const file = ctx.request.files.file; // 获取上传文件
    if (file == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    //检查文件夹是否存在
    //检查上级文件夹是否存在
    console.log("__dirname", __dirname,body.filePath);
    const filename = path.join(__dirname, body.filePath);
  console.log("文件路径", filename);
    const parentDir = path.dirname(filename);
    console.log("文件夹", parentDir);
    if (!fs.existsSync(parentDir)) {
        fs.mkdirSync(parentDir, { recursive: true });
    }
    let reader
    let writer
    try {
        reader = fs.createReadStream(file.filepath);
        writer = fs.createWriteStream(filename);
        reader.pipe(writer);
    } catch
    {
        ctx.body = response.fail('上传失败');
        return;
    }
    ctx.body = response.success('上传成功');
}
);

export { router };

